package com.dinero.pagecontents.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.net.http.SslError
import android.os.Build
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.webkit.WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
import com.android.basekt.base.BaseDataBindingConfig
import com.dinero.pagecontents.R
import com.dinero.deseo.net.addPathCommonParams
import com.dinero.deseo.view.H5Interface
import com.dinero.pagecontents.base.BaseActivity
import com.dinero.pagecontents.databinding.ActivityWebContainerBinding
import com.dinero.pagecontents.viewmodel.WebContainerViewModel


/**
 * @Created on 2021/12/28 11:29
 * @Author
 * @Describe
 */
class WebContainerActivity :
    BaseActivity<ActivityWebContainerBinding, WebContainerViewModel>() {

    var TAG = "WebContainerActivity"
    override fun initView() {
        mBinding.viewModel = mViewModel
        loadWebView()
    }

    override fun initData() {
        mViewModel.finishView.observe(this){
            if (mBinding.webView.canGoBack()) {
                mBinding.webView.goBack() //返回上一页面
            }else{
                finishView()
            }
        }
    }

    /**
     * 获取binding相关配置
     *
     * @return
     */
    override fun getDataBindingConfig(): BaseDataBindingConfig {
        return BaseDataBindingConfig(R.layout.activity_web_container)
    }

    /**
     * 获取viewmodel Clazz
     *
     * @return
     */
    override fun initViewModelClazz(): Class<WebContainerViewModel> {
        return WebContainerViewModel::class.java
    }

    /**
     * 使用x5内核加载pdf
     */
    private fun loadWebView() {
        initWebViewSettings()
//        //监听网页的加载进度
        mBinding.webView.setWebChromeClient(object : WebChromeClient() {
            override fun onProgressChanged(webView: WebView?, i: Int) {
                mBinding.progressHorizontal.setProgress(i)
                mBinding.progressHorizontal.visibility =
                    if (i == 100) View.GONE else View.VISIBLE
            }

            override fun onReceivedTitle(webView: WebView?, s: String) {
                super.onReceivedTitle(webView, s)
                Log.i(TAG, "onReceivedTitle: " + s)
                setTitle(s)
            }
        })
//        if (BuildConfig.DEBUG) {
//            WebView.setWebContentsDebuggingEnabled(true)
//        }
        mBinding.webView.setWebViewClient(client)

        var urlPath = intent.getStringExtra("urlPath")
        Log.i(TAG, "urlPath===>$urlPath")
        urlPath?.let {
            var url = urlPath.addPathCommonParams()
            Log.i(TAG, "loadWebView:urlPath===>$url")
            mBinding.webView.loadUrl(url)
        }

    }

    /**
     * 改写物理按键——返回的逻辑，希望浏览的网页后退而不是退出浏览器
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mBinding.webView.canGoBack()) {
                mBinding.webView.goBack() //返回上一页面
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun finishView() {
        super.finishView()
    }

    private fun setTitle(title: String) {
        mViewModel.mTitleContent.value = title
    }

    private val client: WebViewClient = object : WebViewClient() {
        /**
         * 防止加载网页时调起系统浏览器
         */
        override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
            url?.let { view.loadUrl(it) }
            return true
        }

        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError?) {
            if (dialog == null) {
                val builder: AlertDialog.Builder = AlertDialog.Builder(view.getContext())
                builder.setMessage("Falló la autenticación del certificado SSL. Desea continuar el acceso?")
                builder.setPositiveButton("Confirmar",
                    DialogInterface.OnClickListener { dialog, which ->
                        handler.proceed()
                        dialog.dismiss()
                    })
                builder.setNegativeButton("Cancelar",
                    DialogInterface.OnClickListener { dialog, which ->
                        handler.cancel()
                        dialog.dismiss()
                    })
                dialog = builder.create()
            }
            if (!dialog?.isShowing()!!) {
                dialog?.show()
            }
        }
    }
    var dialog: AlertDialog? = null

    @SuppressLint("JavascriptInterface")
    private fun initWebViewSettings() {
        val webSetting: WebSettings = mBinding.webView.getSettings()
        webSetting.javaScriptEnabled = true

        // 设置可以支持缩放
        webSetting.setSupportZoom(false);
        // 设置出现缩放工具
        webSetting.builtInZoomControls = false;
        //扩大比例的缩放
        webSetting.useWideViewPort = false;
        //自适应屏幕
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
        webSetting.loadWithOverviewMode = true;

        webSetting.allowFileAccess = true

        webSetting.setSupportMultipleWindows(true)
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.mixedContentMode = MIXED_CONTENT_COMPATIBILITY_MODE
        }

        mBinding.webView.addJavascriptInterface(H5Interface(this), "dineroDeseo");
    }

}